﻿<%@ WebHandler Language="C#" Class="ProductLinesHandler" %>

using System;
using System.Web;
using BusinessRule.DTO;
using System.Web.SessionState;
using DatabaseAccess.DBUtility;
using System.Data.OracleClient;
using System.Data;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;
/**
 * Description: MES与产线MES业务
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer:longb
 * create Date:2024-04-01
 */
public class ProductLinesHandler : IHttpHandler, IRequiresSessionState
{
    ApsPlanDownSendBusiness apsPlanDownSendBusiness = new ApsPlanDownSendBusiness();
    uLMSCommonBusiness commonBusiness = new uLMSCommonBusiness();
    uLMSCheckIBusiness checkBusiness = uMESBusinessFactory.instance.GetuLMSCheckObject();
    CurrentUserInfo m_UserInfo;
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            var action = context.Request["action"].ToString();
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            switch (action)
            {
                case "getCustomObjectData"://查询自定义产线属性信息
                    getCustomObjectData(context);
                    break;
                case "sendDownOrderTaskToFms"://下发产线
                    sendDownOrderTaskToFms(context);
                    break;
                case "specstatusChange"://下发撤销、报废
                    specstatusChange(context);
                    break;
                case "MoveNextStep"://产线报工完成--远程调用（自动移动到下一序）
                    MoveNextStep(context);
                    break;
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            var result = new uMESProcessResult();
            result.Result = false;
            result.Message = ex.Message;
            context.Response.ContentType = "text/html";
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
    /// <summary>
    /// 产线报工完成--远程调用（自动移动到下一序）
    /// </summary>
    /// <param name="context"></param>
    private void MoveNextStep(HttpContext context)
    {
        var dic = JsonConvert.DeserializeObject<Dictionary<string, object>>(context.Request["data"].ToString());
        var msg = string.Empty;
        uMESProcessResult result = new uMESProcessResult();

        var sql = @"select csd.containerid,csd.workflowstepid ,cci.workflowid,cci.containername,cci.workflowstepsequence sequence,cci.factoryid
                            from containerstepdispatch csd 
                           left join apsplandetail a on a.containerid =csd.containerid and a.workflowstepid =csd.workflowstepid 
                           left join containercurrentinfo cci on cci.containerid =csd.containerid
                           where csd.isuse =0 and csd.containerstepdispatchid ='" + dic["DispatchID"] + "'";
        DataTable dt = DatabaseHelper.Query_ReturnDatTable(sql);
        var esql = @"SELECT e.FULLNAME,e.EMPLOYEEID FROM EMPLOYEE e WHERE e.EMPLOYEENAME='" + dic["ReportEmpName"] + "'";
        DataTable edt = DatabaseHelper.Query_ReturnDatTable(esql);
        if (dt.Rows.Count > 0)
        {
            DataRow item = dt.Rows[0];
            var factoryid = item["factoryid"].ToString();
            DataTable levelAttributes = commonBusiness.GetFatoryAttributes(factoryid);
            if (m_UserInfo == null)
            {
                m_UserInfo = new CurrentUserInfo();
                m_UserInfo.FactoryID = factoryid;
                m_UserInfo.FullName = edt.Rows.Count > 0 ? edt.Rows[0]["FullName"].ToString() : string.Empty;
                m_UserInfo.EmployeeID = edt.Rows.Count > 0 ? edt.Rows[0]["EmployeeID"].ToString() : string.Empty;
            }

            ServerHostInfo host = new ServerHostInfo();
            host.UserName = System.Configuration.ConfigurationManager.AppSettings["CamstarUserName"].ToString();
            host.Password = System.Configuration.ConfigurationManager.AppSettings["CamstarPassword"].ToString();
            result.Result = checkBusiness.MoveNextStep(new Dictionary<String, String>() {{"ContainerID", item["ContainerID"].ToString()},
                                                                                    {"WorkflowStepID", item["WorkFlowStepID"].ToString()},
                                                                                     {"WorkflowID", item["WorkflowID"].ToString()},
                                                                                    {"Sequence", item["Sequence"].ToString()},
                                                                                    {"ContainerName", item["ContainerName"].ToString()}
                                                                                   }, host, Convert.ToInt32(dic["PassQty"]), levelAttributes, m_UserInfo, ref msg);
            result.Message = msg;
        }
        else
        {
            result.Message = "查询不到相应派工记录，工序移动失败";
        }



        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 查询自定义产线属性信息
    /// </summary>
    /// <param name="context"></param>
    private void getCustomObjectData(HttpContext context)
    {
        var selectSQL = @"select c.customobjectname,item.customobjectitemsid,item.customobjectitemsname 
                    from customobject c 
                    left join customobjectitems item on item.customobjectid =c.customobjectid
                    where c.customobjectname like '%产线%' and item.customobjectitemsdesc like '%产线%' and c.isuse=0 and item.isuse =0 and item.factoryid ='{0}'
                    ORDER BY item.SEQUENCE";
        DataTable dt = DatabaseHelper.Query_ReturnDatTable(string.Format(selectSQL, m_UserInfo.FactoryID));
        DataRow drws = dt.NewRow();
        drws["CUSTOMOBJECTITEMSID"] = "";
        drws["CUSTOMOBJECTITEMSNAME"] = "\u3000";
        dt.Rows.Add(drws);//插入到第一行
        context.Response.Write(JsonConvert.SerializeObject(dt));
    }
    /// <summary>
    /// 工序任务状态变更（撤销、报废）
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public void specstatusChange(HttpContext context)
    {
        DataTable apsdt = JsonConvert.DeserializeObject<DataTable>(context.Request["datas"].ToString());
        var apsplandetailids = context.Request["apsplandetailids"];
        var type = context.Request["type"];
        var arrList = new ArrayList();
        //foreach (var apsplandetailid in apsplandetailids.Split(','))
        foreach (DataRow apsdr in apsdt.Rows)
        {
            try
            {
                var select = @"select m.mfgordername,c2.containerstepdispatchid,'' state ,s.specno,s.specid,sb.specname,c.containername
                       ,c.productid,c.productname,c.productdescription,c.productrevision 
                        from apsplandetail dis
                        left join containercurrentinfo c on c.containerid =dis.containerid
                        left join containerstepdispatch c2 on c2.containerid =dis.containerid and c2.workflowstepid =dis.workflowstepid and c2.isuse =0
                        left join mfgorder m on m.mfgorderid =c.mfgorderid 
                        left join workflowstep ws on ws.workflowstepid =dis.workflowstepid 
                        left join spec s on s.specid =ws.specid or s.specbaseid =ws.specbaseid 
                        left join specbase sb on sb.specbaseid =nvl(ws.specbaseid,s.specbaseid) 
                        where dis.apsplandetailid='{0}'";
                var dt = DatabaseHelper.Query_ReturnDatTable(string.Format(select, apsdr["apsplandetailid"].ToString()));
                DataRow dr = dt.Rows.Count > 0 ? dt.Rows[0] : null;
                if (m_UserInfo.Factory.Contains("机匣"))
                {
                    Dictionary<string, object> dic = new Dictionary<string, object>();
                    dic.Add("MfgOrderName", dr["mfgordername"].ToString());//订单号
                    dic.Add("ContainerName", dr["containername"].ToString());//批次号
                    dic.Add("Description", dr["productname"].ToString());//零件名称
                    dic.Add("SpecNO", dr["specno"].ToString());//工序序号
                    dic.Add("OPDesc", dr["specname"].ToString());//工序名称
                    dic.Add("ContainerStepDispatchID", dr["containerstepdispatchid"].ToString());//派工id
                    dic.Add("State", type.Equals("4") ? "已撤销" : "已报废");//工序状态
                    var data = JsonConvert.SerializeObject(dic);
                    var result = HttpPost("http://vpn.cps93.top:32012/blade-fms/sync/order-status", data);
                    BusinessRule.Common.LogHelp.WriteLog(m_UserInfo.EmployeeName + (type == "4" ? "【撤销】" : "【报废】") + "工序级任务状态变更：" + data + " 返回结果：" + result);
                    var reMsgObj = JsonConvert.DeserializeObject<Result>(result);
                    if (reMsgObj.success)
                    {
                        //下发产线成功,更新工序状态信息
                        arrList.Add(string.Format(@"UPDATE apsplandetail SET status=0,state={0} WHERE apsplandetailid ='{1}'", type, apsdr["apsplandetailid"].ToString()));
                    }
                    else
                    {
                        //下发产线失败、删除对应数据，以防操作错误
                        apsdt.Rows.Remove(apsdr);
                    }
                }
                else {
                   string strSql = @"select * from SPECSTATUSINFO where mfgordername='{0}' and ContainerName='{1}' and SpecNO='{2}' and ContainerStepDispatchID='{3}'";
                   var ssDT = DatabaseHelper.Query_ReturnDatTable(string.Format(strSql, dr["mfgordername"],dr["containername"],dr["specno"],dr["containerstepdispatchid"]));
                    if(ssDT.Rows.Count>0){
                        arrList.Add(string.Format("update SPECSTATUSINFO set state='{0}',updatedate=sysdate where specstatusinfoid='{1}'", type.Equals("4") ? "已撤销" : "已报废", ssDT.Rows[0]["specstatusinfoid"]));
                    }
                }
            }
            catch (Exception ex)
            {
                BusinessRule.Common.LogHelp.WriteLog(m_UserInfo.EmployeeName + (type == "4" ? "撤销" : "报废") + "工序级任务失败：" + apsdr["apsplandetailid"].ToString() + " 异常原因：" + ex.Message);
            }
        }
        uMESProcessResult resultt = new uMESProcessResult();
        resultt.Result = arrList.Count > 0 ? DatabaseHelper.ExecuteSqlListTran(arrList) : false;
        resultt.Message = (type == "4" ? "撤销" : "报废") + (resultt.Result ? "成功" : "失败");
        //回收下发给MES的派工数据
        if (apsdt.Rows.Count > 0 && resultt.Result)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("EmployeeID", m_UserInfo.EmployeeID.ToString());//操作人
            dic.Add("FactoryName", m_UserInfo.Factory);//操作人分厂 
            dic.Add("TeamID", m_UserInfo.TeamID);//班组
            dic.Add("type", "ReCall");//操作类型
            uMESProcessResult resultP = apsPlanDownSendBusiness.SaveApsPlanDatas(dic, apsdt); //先下发到MES成功再执行下发fms 
        }
        context.Response.Write(JsonConvert.SerializeObject(resultt));
    }
    /// <summary>
    /// 下发工序级任务给分厂产线系统
    /// </summary>
    /// <param name="context"></param>
    public void sendDownOrderTaskToFms(HttpContext context)
    {
        DataTable dt = JsonConvert.DeserializeObject<DataTable>(context.Request["datas"].ToString());
        //var apsplandetailids = context.Request["apsplandetailids"];
        DataTable structuralCopy = dt.Copy();
        structuralCopy.Clear();
        Dictionary<string, string> dic = new Dictionary<string, string>();
        dic.Add("EmployeeID", m_UserInfo.EmployeeID.ToString());//操作人
        dic.Add("FactoryName", m_UserInfo.Factory);//操作人分厂 add:Wangjh 20240115
        dic.Add("TeamID", m_UserInfo.TeamID);//班组
        dic.Add("type", context.Request["type"]);//操作类型
        uMESProcessResult resultP = apsPlanDownSendBusiness.SaveApsPlanDatas(dic, dt); //先下发到MES成功再执行下发fms、产线
        uMESProcessResult resultt = new uMESProcessResult();
        var msg = string.Empty;
        if (resultP.Result && m_UserInfo.Factory.Contains("机匣"))
        {
            var arrList = new ArrayList();
            //foreach (var apsplandetailid in apsplandetailids.Split(','))
            foreach (DataRow dr in dt.Rows)
            {
                try
                {
                    DataRow mdtRow = null;
                    var data = getWorkflowStepData(dr["apsplandetailid"].ToString(), out mdtRow);
                    if (mdtRow != null)
                    {
                        if (string.IsNullOrWhiteSpace(mdtRow["PROCESS_NO"].ToString()))
                        {
                            msg += "工艺规程编号为空";
                            structuralCopy.Rows.Add(dr.ItemArray);
                            continue;
                        }

                        var result = HttpPost("http://vpn.cps93.top:32012/blade-fms/sync/order", data);
                        BusinessRule.Common.LogHelp.WriteLog(m_UserInfo.EmployeeName + "【下发】工序级任务给分厂产线系统：" + data + " 返回结果：" + result);
                        var reMsgObj = JsonConvert.DeserializeObject<Result>(result);
                        if (reMsgObj.success)
                        {
                            //下发产线成功,更新工序状态信息
                            arrList.Add(string.Format(@"UPDATE apsplandetail SET status=1,state=1 WHERE apsplandetailid ='{0}'", dr["apsplandetailid"].ToString()));
                        }
                        else
                        {
                            //下发产线失败,删除下发的数据集对应行数据
                            structuralCopy.Rows.Add(dr.ItemArray);
                            msg += reMsgObj.msg;
                        }
                    }
                }
                catch (Exception ex)
                {
                    structuralCopy.Rows.Add(dr.ItemArray);
                    BusinessRule.Common.LogHelp.WriteLog("下发工序级任务给分厂产线系统失败：" + dr["apsplandetailid"].ToString() + " 异常原因：" + ex.Message);
                }
            }
            //要下发的排产数据，如果有下发不成功的，要对下个MES的进行回收撤销
            if (structuralCopy.Rows.Count > 0)
            {
                dic["type"] = "ReCall";
                uMESProcessResult ReCall = apsPlanDownSendBusiness.SaveApsPlanDatas(dic, structuralCopy);
            }
            resultt.Result = arrList.Count > 0 ? DatabaseHelper.ExecuteSqlListTran(arrList) : false;
        }
        else
        {

            resultt.Result = sendDownOrderTaskToOther(dt);
        }
        resultt.Message = (resultt.Result ? "下发成功 " : "下发失败 ") + msg;
        context.Response.Write(JsonConvert.SerializeObject(resultt));
    }
    /// <summary>
    /// 其他产线走数据中心表触发方式
    /// </summary>
    /// <param name="dt"></param>
    /// <returns></returns>
    private bool sendDownOrderTaskToOther(DataTable dt)
    {
        string insertSpecstatusinfo = @"INSERT INTO SPECSTATUSINFO
                    (MFGORDERNAME, CONTAINERNAME, DESCRIPTION, SPECNO, CONTAINERSTEPDISPATCHID, OPDESC, STATE, CREATEDATE)
                    VALUES('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', sysdate);";
        var arrList = new ArrayList();
        foreach (DataRow row in dt.Rows)
        {
            var select = @"select m.mfgordername,c.ContainerName,c.productname,s.specno,sb.specname,ds.containerstepdispatchid,'1' state
                        from apsplandetail  dis
                        left join containerstepdispatch ds on ds.containerid =dis.containerid and ds.workflowstepid =dis.workflowstepid and ds.isuse=0
                        left join containercurrentinfo c on c.containerid =dis.containerid 
                        left join mfgorder m on m.mfgorderid =c.mfgorderid 
                        left join workflowstep ws on ws.workflowstepid =dis.workflowstepid 
                        left join spec s on s.specid =ws.specid or s.specbaseid =ws.specbaseid 
                        left join specbase sb on sb.specbaseid =nvl(ws.specbaseid,s.specbaseid) 
                        where  dis.apsplandetailid ='{1}'";
            var dtdata = DatabaseHelper.Query_ReturnDatTable(string.Format(select, row["apsplandetailid"]));
            DataRow dr = dtdata.Rows.Count > 0 ? dtdata.Rows[0] : null;
            if (dr != null)
            {
                arrList.Add(string.Format(insertSpecstatusinfo, dr["mfgordername"], dr["ContainerName"], dr["productname"], dr["specno"], dr["containerstepdispatchid"], dr["specname"], dr["state"]));
            }
        }
        return DatabaseHelper.ExecuteSqlListTran(arrList);
    }

    private string getWorkflowStepData(string apsplandetailid, out DataRow mdtRow)
    {
        var select = @"select m.mfgordername,ds.containerstepdispatchid,'' state ,s.specno,s.specid,sb.specname ,ds.qty,to_char(ds.plannedstartdate,'yyyy-MM-dd hh24:mi:ss') plannedstartdate,to_char(ds.plannedfinishdate,'yyyy-MM-dd hh24:mi:ss') plannedfinishdate,c.ContainerName
                        ,empl.fullname,empl.employeename,c.productid,c.productname,c.productdescription,c.productrevision ,w.part_revid,w.process_no,w.workflowrevision,w.ly2sequence,
                        ws.makecycle,ws.preparecycle,ws.transfercycle, r.resourcename ,r.description,'' resourceattribute,dis.workflowstepid 
                        from apsplandetail  dis
                        left join containerstepdispatch ds on ds.containerid =dis.containerid and ds.workflowstepid =dis.workflowstepid and ds.isuse=0
                        left join containercurrentinfo c on c.containerid =dis.containerid 
                        left join mfgorder m on m.mfgorderid =c.mfgorderid 
                        left join workflowstep ws on ws.workflowstepid =dis.workflowstepid 
                        left join spec s on s.specid =ws.specid or s.specbaseid =ws.specbaseid 
                        left join specbase sb on sb.specbaseid =nvl(ws.specbaseid,s.specbaseid) 
                        left join employee empl on empl.employeeid='{0}'
                        left join workflow w on w.workflowid =ws.workflowid 
                        left join resourcedef r on r.resourceid =dis.resourceid
                        where  dis.apsplandetailid ='{1}'";
        var dt = DatabaseHelper.Query_ReturnDatTable(string.Format(select, m_UserInfo.EmployeeID, apsplandetailid));
        DataRow dr = dt.Rows.Count > 0 ? dt.Rows[0] : null;
        mdtRow = dr;

        Dictionary<string, Object> data = new Dictionary<string, object>();
        data.Add("ContainerName", dr == null ? "" : dr["ContainerName"]);//批次号
        data.Add("MfgOrderName", dr == null ? "" : dr["mfgordername"]);//订单号
        data.Add("ContainerStepDispatchID", dr == null ? "" : dr["containerstepdispatchid"]);//派工ID
        data.Add("State", dr == null ? "" : dr["state"]);//工序状态
        data.Add("SpecNO", dr == null ? "" : dr["specno"]);//工序序号
        data.Add("SPECID", dr == null ? "" : dr["specid"]);//工序唯一标识
        data.Add("OPDesc", dr == null ? "" : dr["specname"]);//工序名称
        data.Add("Qty", dr == null ? "" : dr["qty"]);//在制数量
        data.Add("StartTime", dr == null ? "" : dr["plannedstartdate"]);//计划开始时间
        data.Add("Endtime", dr == null ? "" : dr["plannedfinishdate"]);//计划结束时间
        data.Add("EmployeeName", dr == null ? "" : dr["employeename"]);//派工人员工号
        data.Add("FullName", dr == null ? "" : dr["fullname"]);//派工人员名称
        data.Add("ProductID", dr == null ? "" : dr["productid"]);//零件ID
        data.Add("ProductName", dr == null ? "" : dr["productname"]);//零件号
        data.Add("Description", dr == null ? "" : dr["productdescription"]);//零件名称
        data.Add("ProductRevision", dr == null ? "" : dr["productrevision"]);//零件版本
        data.Add("Part_RevID", dr == null ? "" : dr["part_revid"]);//设计图版次
        data.Add("Process_no", dr == null ? "" : dr["process_no"]);//工艺规程编号
        data.Add("WorkflowRevision", dr == null ? "" : dr["workflowrevision"]);//工艺规程版本
        data.Add("ly2sequence", dr == null ? "" : dr["ly2sequence"]);//工艺规程版次
        data.Add("MakeCycle", dr == null ? "" : dr["makecycle"]);//单件工时
        data.Add("PrepareCycle", dr == null ? "" : dr["preparecycle"]);//准备工时
        data.Add("TransferCycle", dr == null ? "" : dr["transfercycle"]);//运转工时
        data.Add("dispatchResourceName", dr == null ? "" : dr["resourcename"]);//派工设备编码
        data.Add("dispatchDescription", dr == null ? "" : dr["description"]);//派工设备名称
        data.Add("ResourceAttribute", dr == null ? "" : dr["resourceattribute"]);//关联产线

        data.Add("Steps", getStepInfoData(dr["workflowstepid"].ToString()));
        data.Add("FileUrls", getworkflowFiles(dr["workflowstepid"].ToString()).Split(','));
        return JsonConvert.SerializeObject(data);
    }

    private List<Dictionary<string, Object>> getStepInfoData(string workflowStepID)
    {
        List<Dictionary<string, Object>> stepList = new List<Dictionary<string, object>>();
        var selectStep = @"select sob.stepinfoname,so.stepinfoid,so.revision,so.stepseq,so.stepno,st.spectypename,ws.workflowstepname,so.workflowstepid,so.stepno||'-'||so.description stepinfodesc
                                from stepinfobase sob
                                left join stepinfo so on so.stepinfoid = sob.revofrcdid  
                                left join workflowstep ws on ws.workflowstepid=so.workflowstepid 
                                left join spectype st on st.spectypeid = so.spectypeid 
                                where so.workflowstepid='{0}'  
                                order by ws.sequence,so.stepno,so.stepseq ASC ";
        var selectCheckPoint = @"select wfs.workflowstepname,sc.basevalue,sc.floorfloat,sc.ceilfloat,sc.bubblenumber ,sc.workflowstepid,sc.stepinfoid,sc.singlesign,sc.checkno,sc.stepcheckpointid,sc.inputnum checkfrep,sc.CheckMethod
                                 from stepcheckpoint sc
                                 inner join workflowstep wfs on sc.workflowstepid=wfs.workflowstepid
                                 where sc.stepinfoid='{0}'
                                 order by sc.bubblenumber ";
        var selectCuttool = @"select t.sequence,t.qty, ct.cuttoolid toolid, ct.cuttoolname toolname,ct.drawingno||'/'||ct.specification ,ct.description,rt.resourcetypename 
                               from stepinfotools t
                               left join cuttool ct  on ct.cuttoolid = t.tools
                               left join resourcetype rt  on rt.resourcetypeid = ct.resourcetypeid
                               where ct.cuttoolid <> ' ' and t.stepinfoid='{0}'";
        var selectSpecialtool = @"select t.sequence,t.qty, st.specialtoolid toolid, st.specialtoolname toolname,st.drawingno||'/'||st.specification,st.description,rt.resourcetypename 
                           from stepinfotools t
                           left join specialtool st  on st.specialtoolid = t.tools
                           left join resourcetype rt  on rt.resourcetypeid = st.resourcetypeid
                           where st.specialtoolid <> ' ' and t.stepinfoid='{0}'";

        //工序下的检测项信息
        var stepDT = DatabaseHelper.Query_ReturnDatTable(string.Format(selectStep, workflowStepID));
        foreach (DataRow dr in stepDT.Rows)
        {
            Dictionary<string, Object> step = new Dictionary<string, object>();
            step.Add("StepInfoID", dr["stepinfoid"]);//工步ID
            step.Add("StepSeq", dr["stepseq"]);//工步顺序
            step.Add("StepNO", "GX000005");//dr["stepno"]);//工步号
            step.Add("Description", dr["stepinfoName"]);//工步名称
            step.Add("SpecType", "");
            //step.Add("stepinfodesc", dr["stepinfodesc"]);

            //工步下的检测项信息
            var checkpointDT = DatabaseHelper.Query_ReturnDatTable(string.Format(selectCheckPoint, dr["stepinfoid"]));
            List<Dictionary<string, Object>> checkpointList = new List<Dictionary<string, object>>();
            foreach (DataRow cpdr in checkpointDT.Rows)
            {
                Dictionary<string, Object> cp = new Dictionary<string, object>();
                cp.Add("StepCheckPointID", cpdr["stepcheckpointid"]);//检测项ID
                cp.Add("CheckNO", cpdr["checkno"]);//顺序号
                cp.Add("BubbleNumber", cpdr["bubblenumber"]);//气泡号
                cp.Add("BaseValue", cpdr["basevalue"]);//理论值
                cp.Add("FloorFloat", cpdr["floorfloat"]);//上公差
                cp.Add("CeilFloat", cpdr["ceilfloat"]);//下公差
                cp.Add("SingleSign", cpdr["singlesign"]);//单向标识
                cp.Add("CheckFrep", cpdr["checkfrep"]);//检测次数
                cp.Add("CheckMethod", cpdr["CheckMethod"]);//检测手段
                checkpointList.Add(cp);
            }
            step.Add("DetectionItemIds", checkpointList);

            //工步下的刀具
            var cuttoolDT = DatabaseHelper.Query_ReturnDatTable(string.Format(selectCuttool, dr["stepinfoid"]));
            List<Dictionary<string, Object>> cuttoolList = new List<Dictionary<string, object>>();
            foreach (DataRow ctdr in cuttoolDT.Rows)
            {
                Dictionary<string, Object> ct = new Dictionary<string, object>();
                ct.Add("CutToolID", ctdr["toolid"]);//唯一ID
                ct.Add("CutToolName", "1");//ctdr["toolname"]);//刀具资源编号
                ct.Add("Description", ctdr["description"]);//刀具名称(描述) 刀具资源名称
                ct.Add("Qty", ctdr["qty"]);//刀具资源数量
                //ct.Add("resourcetypename", ctdr["resourcetypename"]);//工具类型
                //ct.Add("sequence", ctdr["sequence"]);//顺序号
                cuttoolList.Add(ct);
            }
            step.Add("ToolList", cuttoolList);
            //工步下的夹模具
            var specialtoolDT = DatabaseHelper.Query_ReturnDatTable(string.Format(selectSpecialtool, dr["stepinfoid"]));
            List<Dictionary<string, Object>> specialtoolList = new List<Dictionary<string, object>>();
            foreach (DataRow stdr in specialtoolDT.Rows)
            {
                Dictionary<string, Object> st = new Dictionary<string, object>();
                st.Add("SpecialToolID", stdr["toolid"]);//唯一ID
                st.Add("SpecialToolName", "1");//stdr["toolname"]);//刀具名称
                st.Add("Description", stdr["description"]);//刀具描述
                st.Add("Qty", stdr["qty"]);//数量
                //st.Add("resourcetypename", stdr["resourcetypename"]);//工具类型
                //st.Add("sequence", stdr["sequence"]);//顺序号
                specialtoolList.Add(st);
            }
            step.Add("FixtureAssets", specialtoolList);
            stepList.Add(step);
        }
        return stepList;
    }

    /// <summary>
    /// 根据工序ID查询工艺附件
    /// </summary>
    /// <param name="workflowStepID">工序ID</param>
    /// <returns></returns>
    private string getworkflowFiles(string workflowStepID)
    {
        var hostUrl = "htttp://10.15.7.76/InSiteWebApplication/";
        var selectFile = @"SELECT wm_concat('{0}'||o.FILEPATH) filepath FROM OBJECTDOCINFO o WHERE o.PARENTID ='{1}'";
        var fileDt = DatabaseHelper.Query_ReturnDatTable(string.Format(selectFile, hostUrl, "00062c8000004f67"));
        return fileDt.Rows.Count > 0 ? fileDt.Rows[0]["filepath"].ToString() : "";
    }


    public string HttpPost(string url, string body)
    {
        var content = new System.Net.Http.StringContent(body, Encoding.UTF8, "application/json");
        System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
        try
        {
            var response = client.PostAsync(url, content);
            var responseContent = response.Result.Content.ReadAsStringAsync();
            return responseContent.Result.ToString();
        }
        catch (Exception ex)
        {
            return "{code:'101',msg:" + ex.Message + "}";
        }
    }



    public class Result
    {
        public string code { set; get; }
        public Boolean success { set; get; }
        public string data { set; get; }
        public string msg { set; get; }
    }

}